/*
 * @Author: wuqingchun
 * @Date: 2024-10-29 20:36:52
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-10-30 11:23:16
 */
#include "libnet_error.h"
#include "net_connection_helper.h"


CNetConnectionActive* CNetConnectionHelper::CreateActive(INetEventHandler* pobjEventHandler, INetTCPConnectionCallback* pobjCallback, const sockaddr_in *pstAddr)
{
    if (pobjEventHandler == nullptr || pobjCallback == nullptr || pstAddr == nullptr)
    {
        return nullptr;
    }

    CNetConnectionActive* pobjConn = new (std::nothrow) CNetConnectionActive(*pobjEventHandler, *pobjCallback, *pstAddr);
    if (pobjConn == nullptr)
    {
        return nullptr;
    }

    if (pobjConn->Init() == ERROR_SUCCESS)
    {
        return pobjConn;
    }

    delete pobjConn;
    
    return nullptr;
}

CNetConnectionListener* CNetConnectionHelper::CreateListener(INetEventHandler* pobjEventHandler, INetTCPConnectionCallback* pobjCallback, const sockaddr_in *pstAddr)
{
    if (pobjEventHandler == nullptr || pobjCallback == nullptr || pstAddr == nullptr)
    {
        return nullptr;
    }

    CNetConnectionListener* pobjConn = new (std::nothrow) CNetConnectionListener(*pobjEventHandler, *pobjCallback, *pstAddr);
    if (pobjConn == nullptr)
    {
        return nullptr;
    }

    if (pobjConn->Init() == ERROR_SUCCESS)
    {
        return pobjConn;
    }

    delete pobjConn;

    return nullptr;
}

CNetConnectionPassive* CNetConnectionHelper::CreatePassive(INetEventHandler* pobjEventHandler, INetTCPConnectionCallback* pobjCallback, const sockaddr_in *pstAddr, int iListenerFd)
{
    if (pobjEventHandler == nullptr || pobjCallback == nullptr || iListenerFd == -1)
    {
        return nullptr;
    }

    CNetConnectionPassive* pobjConn = new (std::nothrow) CNetConnectionPassive(*pobjEventHandler, *pobjCallback, *pstAddr, iListenerFd);
    if (pobjConn == nullptr)
    {
        return nullptr;
    }

    if (pobjConn->Init() == ERROR_SUCCESS)
    {
        return pobjConn;
    }

    delete pobjConn;
    
    return nullptr;
}
